<template>
  <div class="manage">
    <el-dialog
      :title="dialogForm.type === 'add' ? '新增模板' : '更新模板'"
      :visible.sync="dialogForm.isShow"
      width="500px"
    >
      <CommonForm
        ref="myform"
        :formItemList="dialogForm.formItemList"
        :formData="dialogForm.formData"
        :inline="dialogForm.inline"
        :rules="dialogForm.rules"
      ></CommonForm>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogForm.isShow = false">取消</el-button>
        <el-button type="plain" @click="confirm">确定</el-button>
      </div>
    </el-dialog>


    <!-- 模板预览 -->
    <el-dialog
      :title="'模板预览'"
      :visible.sync="isShowModule"
      width="900px"
    >
      <div v-if="isShowModule">
        <pre style="min-height: 500px;font-size: 14px;"><code class="language-javascript line-numbers">{{moduleText}}</code></pre>
      </div>


      <div slot="footer" class="dialog-footer">
        <el-button @click="isShowModule = false">取消</el-button>
      </div>
    </el-dialog>

    <!-- 设置模板变量 -->
    <el-dialog
      :title="'设置模板变量'"
      :visible.sync="isShowModuleVars"
      width="400px"
    >
      <div>

        <form class="form">
          <div v-for="param in params" :key="param" class="form__item">
            <label :for="param" class="form__label">{{ param }}</label>
            <input type="text" :id="param" v-model="paramFormData[param]" class="form__input">
          </div>
        </form>

      </div>


      <div slot="footer" class="dialog-footer">
        <el-button @click="isShowModuleVars = false">取消</el-button>
        <el-button type="primary" @click="doSetVars">保存</el-button>
      </div>
    </el-dialog>

    <!-- 搜索 -->
    <div class="manage-header">
      <CommonForm
        :formItemList="searchForm.formItemList"
        :formData="searchForm.formData"
        :inline="searchForm.inline"
      >
        <el-button type="plain" @click="search" size="mini">搜索 <i class="el-icon-search"/></el-button>
        <el-button type="plain" class='reset' @click="reset" size="mini">重置 <i class="el-icon-refresh-left"/></el-button>
      </CommonForm>
    </div>

    <!-- 按钮区 -->
    <div style="margin-bottom: 5px">

      <el-button type="plain" @click="handleAdd" size="mini"
      >新增 <i class="el-icon-circle-plus-outline"></i>
      </el-button>
      <el-popconfirm
        style="margin-left: 10px"
        confirm-button-text='确定'
        cancel-button-text='我再想想'
        icon="el-icon-info"
        icon-color="red"
        title="你确定删除吗？"
        @confirm="handleDeleteBatch"
      >
        <el-button type="plain" size="mini" slot="reference"
        >批量删除 <i class="el-icon-remove-outline"></i>
        </el-button>
      </el-popconfirm>

    </div>

    <!--    数据表格-->
    <CommonTable
      :tableData="table.tableData"
      :tableLabel="table.tableLabel"
      :pageConfig="table.pageConfig"
    >
      <template>
<!--        <el-button title="设置变量"  type="plain" @click="setVars(data)"> <i class="el-icon-user"/></el-button>-->
      </template>
    </CommonTable>
  </div>
</template>



<script>
import CommonForm from '../../../components/CommonForm'
import CommonTable from '../../../components/CommonTable'
import Prism from 'prismjs'

import {
  add,
  getList,
  deleteOne,
  edit,
  deleteBatch
} from '../../../api/module'
import {findDataForSelect} from '../../../api/project'

export default {
  name: 'Module',
  components: {
    CommonForm,
    CommonTable
  },
  data() {
    return {
      projectOptions: [],
      moduleText: '',
      dialogForm: {
        type: 'add', // add为新增，edit为编辑
        isShow: false,
        formItemList: [
          {
            name: 'name',
            label: '模板名称',
            type: 'input',
          },
          {
            name: 'projectId',
            label: '所属项目',
            type: 'select',
            icon: 'el-icon-search',
            optionList: []
          },
          // {
          //   name: 'groupName',
          //   label: '组名',
          //   type: 'input'
          // },
          {
            name: 'type',
            label: '类型',
            type: 'select',
            optionList: [
              {
                name: '默认',
                id: '默认'
              },
              {
                name: '其他',
                id: '其他'
              },
              {
                name: 'controller',
                id: 'controller'
              },
              {
                name: 'Service',
                id: 'Service'
              },
              {
                name: 'ServiceImpl',
                id: 'ServiceImpl'
              },
              {
                name: 'Mapper.java',
                id: 'Mapper.java'
              },
              {
                name: 'Mapper.xml',
                id: 'Mapper.xml'
              },
              {
                name: 'Entity',
                id: 'Entity'
              },
              {
                name: 'Req',
                id: 'Req'
              },
              {
                name: 'Dto',
                id: 'Dto'
              },
              {
                name: 'Vo',
                id: 'Vo'
              },
              {
                name: 'Import',
                id: 'Import'
              },
              {
                name: 'Export',
                id: 'Export'
              }
            ]
          },
          {
            name: 'content',
            label: '模板内容',
            type: 'textarea'
          }
        ],
        formData: {},
        inline: true,
        rules: {
          name: [{required: true, message: '请输入模板名称', trigger: 'blur'}],
          // packageName: [{required: true, message: '请输入包名', trigger: 'blur'}],
          projectId: [{required: true, message: '请输入所属项目', trigger: 'blur'}],
          content: [{required: true, message: '请输入模板内容', trigger: 'blur'}],
        }
      },
      searchForm: {
        formItemList: [
          {
            name: 'projectId',
            label: '所属项目',
            type: 'select',
            icon: 'el-icon-search',
            optionList: []
          }
        ],
        formData: {
          project: ''
        },
        inline: true
      },

      table: {
        tableData: [],
        tableLabel: [
          {
            name: 'name',
            label: '模板名称',
            type: 'column',
            width: 60
          },
          {
            name: 'content',
            label: '内容',
            type: 'link'
          },
          {
            name: 'projectName',
            label: '所属项目',
            type: 'column'
          },
          {
            name: 'type',
            label: '类别',
            type: 'column'
          },
          {
            name: 'createUserName',
            label: '作者',
            type: 'column',
            width: 50
          }
        ],
        pageConfig: {
          total: 10, // 记录总数
          current: 1, // 起始页
          size: 10 // 每页展示的记录数
        }
      },
      ids: [],
      isShowModule:false, //预览模板
      isShowModuleVars:false,  //模板变量参数
      params:[], //当前模板参数
      paramFormData:{},
      id:null, //当前模板ID
    }
  },
  computed: {
    // 获取导入数据的接口
    importApi() {
      return getImportApi()
    },
    headers() {
      return {
        token: localStorage.getItem("token")
      }
    }
  },
  methods: {

    loadProjects() {
      findDataForSelect().then(response => {
        console.log(response.data)
        response.data.forEach(obj => {
          // 只是作为演示，如果有字段不同，不劳烦后端处理了
          if (obj.hasOwnProperty('tableName')) {
            obj.name = obj.tableName;
            delete obj.tableName; // 删除原来的tableName属性（可选）
          }
        });
        this.projectOptions = response.data;
        this.searchForm.formItemList[0].optionList = this.projectOptions;
        this.dialogForm.formItemList[1].optionList = this.projectOptions;

      });
    },

    /**
     * 预览模板
     */
    triggerLink(row) {
      this.isShowModule = true;
      this.moduleText = row.content;
      // alert(row.content)
      /*let params = this.getParams(this.moduleText)
      console.log(params)*/
      setTimeout(() => {
        Prism.highlightAll()
      }, 200)
    },

    /**
     * 单个删除
     * @param id
     */
    handleDelete(id) {
      deleteOne(id).then(
        response => {
          if (response.code === 200) {
            this.$message.success("删除成功！")
            this.loading()
          } else {
            this.$message.error("删除失败！")
          }
        }
      )
    },
    /**
     * 批量删除
     */
    handleDeleteBatch() {
      if (!this.ids.length) {
        this.$message.error("请至少勾选一个 模板！")
        return
      }
      deleteBatch(this.ids).then(response => {
        if (response.code === 200) {
          this.$message.success("批量删除成功！")
          this.loading()
        } else {
          this.$message.error("批量删除失败！")
        }
      })
    },
    /**
     * 打开编辑页面
     * @param row
     */
    handleEdit(row) {
      this.dialogForm.isShow = true
      this.dialogForm.type = 'edit'
      row.projectId = row.projectId - 0;
      this.dialogForm.formData = row
    },
    /**
     * 新增 或 修改
     */
    confirm() {
      this.$refs.myform.$refs.form.validate(valid => {  //表单提交时的验证

        if (valid) {
          // 通过type来判断是新增还是编辑
          if (this.dialogForm.type === 'add') {
            //根据模板自动计算参数
            let formData = this.dialogForm.formData;

            const jsonData = {}
            this.params = this.getParams(formData.content)
            for (const param of this.params) {
              jsonData[param] = ''
            }

            formData.params = JSON.stringify(jsonData)
            add(formData).then((response) => {
              if (response.code === 200) {
                this.$message.success("添加成功！")
                this.dialogForm.isShow = false
                this.loading()
              } else {
                this.$message.error("添加失败！")
              }
            })
          } else {
            edit(this.dialogForm.formData).then((response) => {
              if (response.code === 200) {
                this.$message.success("修改成功！")
                this.dialogForm.isShow = false
                this.loading()
              } else {
                this.$message.error("修改失败！")
              }
            })
          }
        }
      });


    },
    search() {
      this.loading()
    },
    // 重置搜索表单
    reset() {
      this.searchForm.formData = {}
      this.loading()
    },
    // 将数据渲染到模板
    loading() {
      this.load();

      getList({
        current: this.table.pageConfig.current,
        size: this.table.pageConfig.size,
        ... this.searchForm.formData
      }).then(response => {
        if (response.code === 200) {
          this.table.tableData = response.data.list
          this.table.pageConfig.total = response.data.total
        } else {
          this.$message.error(response.message)
        }
      })
    },

    /**
     *     点击新增按钮，弹出对话框
     */
    handleAdd() {
      this.dialogForm.isShow = true
      this.dialogForm.type = 'add'
      this.dialogForm.formData = {}
    },

    /**
     * 获取模板中的变量参数
     * @param str
     * @returns {any[]}
     */
    getParams(str) {
      const reg = /\$\{(.+?)\}/g;
      const set = new Set();
      let result;
      while ((result = reg.exec(str)) !== null) {
        const param = result[1];
        set.add(param);
      }
      return Array.from(set);
    },

    /**
     * 打开模板参数配置
     */
    setVars(row) {
      this.isShowModuleVars = true;
      // this.params = this.getParams(row.obj.content);
      this.id = row.obj.id;
      let params = JSON.parse(row.obj.params);
      for(let key in params){
        this.paramFormData[key] = params[key]
        this.params.push(key)
      }
    },

    /**
     * 保存模板参数
     */
    doSetVars() {
      const jsonData = {}
      for (const param of this.params) {
        jsonData[param] = this.paramFormData[param]
      }
      let data = {id: this.id, params: JSON.stringify(jsonData)};

      //更新参数
      edit(data).then((response) => {
        if (response.code === 200) {
          this.$message.success("参数设置成功！")
          this.isShowModuleVars = false;
          this.loading()
        } else {
          this.$message.error("修改失败！")
        }
      })
    },

  },


    created() {
      this.search()
      this.loadProjects()
    },
    mounted() {
      Prism.highlightAll()
      this.$bus.$on("currentChange", current => {
        this.table.pageConfig.current = current
        this.loading()
      })
      this.$bus.$on("del", row => {
        this.handleDelete(row.id)
      })
      this.$bus.$on("edit", row => {
        this.handleEdit(row)
      })
      this.$bus.$on("selectionChange", val => {
        this.ids = val.map(item => item.id) // [{},{},{}] => [1,2,3]
      })
    },
  beforeDestroy() {
    // 销毁事件
    this.$bus.$off("sizeChange")
    this.$bus.$off("currentChange")
    this.$bus.$off("del")
    this.$bus.$off("edit")
    this.$bus.$off("selectionChange")
  }

}


</script>


<style lang="less" scoped>

.form {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.form__item {
  margin-bottom: 16px;
}

.form__label {
  display: block;
  margin-bottom: 8px;
  font-weight: bold;
}

.form__input {
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
  width: 300px;
  font-size: 16px;
}

.form__submit {
  margin-top: 16px;
  padding: 8px 16px;
  background-color: #3f51b5;
  color: #fff;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
}

.form__submit:hover {
  background-color: #283593;
}

</style>
